package com.dragon.modules.yuegou.client.wechat.client.impl;

import com.dragon.modules.yuegou.client.wechat.client.PayBankClient;
import com.dragon.modules.yuegou.client.wechat.model.XmlUtil;
import com.dragon.modules.yuegou.client.wechat.request.PayBankRequest;
import com.dragon.modules.yuegou.client.wechat.request.PayUserRequest;
import com.dragon.modules.yuegou.client.wechat.response.PayBankResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

public class PayBankClientImpl implements PayBankClient {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private ResourceLoader resourceLoader;

    public PayBankClientImpl(ResourceLoader resourceLoader){
        this.resourceLoader = resourceLoader;
    }

    @Override
    public PayBankResponse mmpaysptrans(PayBankRequest request) {
        KeyStore keyStore  =null;
        InputStream instream = null;
        CloseableHttpResponse res = null;
        CloseableHttpClient httpclient = null;
        try {
            keyStore  = KeyStore.getInstance("PKCS12");
            logger.debug("检验是否更新.....");
            Resource certFile =  resourceLoader.getResource("classpath:appcert/apiclient_cert.p12");
            keyStore.load(certFile.getInputStream(), request.getMchId().toCharArray());

            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, request.getMchId().toCharArray())
                    .build();
            // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[] { "TLSv1" },
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            httpclient= HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();

            HttpPost httppost = new HttpPost(request.getUrl());
            System.out.println("executing request" + httppost.getRequestLine());
            System.out.println("request getRequestXml" + request.getRequestXml());
            StringEntity reqEntity = new StringEntity(request.getRequestXml(), "UTF-8");
            httppost.setEntity(reqEntity);
            httppost.setHeader("Content-Type", "application/xml");
            res = httpclient.execute(httppost);

            HttpEntity entity = res.getEntity();
            logger.info(res.getStatusLine().toString());
            StringBuffer XML = new StringBuffer();
            if (entity != null) {
                logger.info("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    XML.append(text);
                }
            }
            logger.info("微信付款到银行卡申请xml:------------------------------------"+XML.toString());
            System.out.println("微信付款到银行卡申请xml:------------------------------------"+XML.toString());
            EntityUtils.consume(entity);
            Document document = DocumentHelper.parseText(XML.toString());
            Element root = document.getRootElement();
            logger.debug(root.toString());
            String return_code = XmlUtil.getText(root.element("return_code"));
            String result_code = XmlUtil.getText(root.element("result_code"));
            String return_msg = XmlUtil.getText(root.element("return_msg"));
            logger.debug("result_code===="+return_code);
            //返回成功 修改退款信息
            PayBankResponse response = new PayBankResponse();
            response.setReturnMsg(return_msg);
            if("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)){
                response.setReturnCode(return_code);

            }
            return response;
        } catch(Exception e){
            logger.warn("微信付款到银行卡申请异常--->" + e.getMessage(), e);
        }finally {
            if(instream!=null){
                try {
                    instream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(res!=null){
                try {
                    res.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpclient!=null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    @Override
    public PayBankResponse transfers(PayUserRequest request) {
        KeyStore keyStore  =null;
        InputStream instream = null;
        CloseableHttpResponse res = null;
        CloseableHttpClient httpclient = null;
        try {
            keyStore  = KeyStore.getInstance("PKCS12");
            logger.debug("检验是否更新.....");
            Resource certFile =  resourceLoader.getResource("classpath:appcert/apiclient_cert.p12");
            keyStore.load(certFile.getInputStream(), request.getMchId().toCharArray());

            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, request.getMchId().toCharArray())
                    .build();
            // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[] { "TLSv1" },
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            httpclient= HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();
            HttpPost httppost = new HttpPost(request.getUrl());
            System.out.println("executing request" + httppost.getRequestLine());
            System.out.println("request getRequestXml" + request.getRequestXml());
            StringEntity reqEntity = new StringEntity(request.getRequestXml(), "UTF-8");
            httppost.setEntity(reqEntity);
            httppost.setHeader("Content-Type", "application/xml");
            res = httpclient.execute(httppost);

            HttpEntity entity = res.getEntity();
            logger.info(res.getStatusLine().toString());
            StringBuffer XML = new StringBuffer();
            if (entity != null) {
                logger.info("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    XML.append(text);
                }
            }
            logger.info("微信付款到个人用户申请xml:------------------------------------"+XML.toString());
            System.out.println("微信付款到个人用户申请xml:------------------------------------"+XML.toString());
            EntityUtils.consume(entity);
            Document document = DocumentHelper.parseText(XML.toString());
            Element root = document.getRootElement();
            logger.debug(root.toString());
            String return_code = XmlUtil.getText(root.element("return_code"));
            String result_code = XmlUtil.getText(root.element("result_code"));
            String return_msg = XmlUtil.getText(root.element("return_msg"));
            logger.debug("result_code===="+return_code);
            //返回成功
            PayBankResponse response = new PayBankResponse();
            response.setReturnMsg(return_msg);
            if("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)){
                response.setReturnCode(return_code);

            }
            return response;
        } catch(Exception e){
            logger.warn("微信付款到个人用户申请异常--->" + e.getStackTrace(), e);
            logger.warn("微信付款到个人用户申请异常--->" + e.getLocalizedMessage(), e);
        }finally {
            if(instream!=null){
                try {
                    instream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(res!=null){
                try {
                    res.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpclient!=null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

}
